package cn.chinasyq.photoquan.user.activity;

import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import cn.chinasyq.photoquan.AppConstant;
import cn.chinasyq.photoquan.R;
import cn.chinasyq.photoquan.news.mode.NewsMode;
import cn.chinasyq.photoquan.photo.GameParticipateInfoActivity;
import cn.chinasyq.photoquan.user.adapter.GameOrderListAdapter;
import cn.chinasyq.photoquan.user.bean.GameOrder;
import cn.chinasyq.photoquan.user.mode.UserMode;
import cn.chinasyq.photoquan.util.BitmapUtil;
import cn.chinasyq.photoquan.util.CameraHead;
import cn.chinasyq.photoquan.util.DialogUtil;
import cn.chinasyq.photoquan.util.TimeUtil;
import cn.chinasyq.photoquan.view.LoadView;
import cn.master.util.utils.ToastUtil;
import cn.master.volley.models.response.handler.ResponseHandler;
import cn.master.xlistview.view.XListView;

/**
 * Created by 一搏 on 2015/11/27.
 */
public class MyGamesActivity extends Activity implements View.OnClickListener, XListView.IXListViewListener, XListView.RefreshTimeListener, ResponseHandler.OnSucceedListener, ResponseHandler.OnFailedListener, ResponseHandler.OnUploadingListener, ResponseHandler.OnNeedLoginListener {
    private static final String TAG_UPLOAD = "upload";
    private static final String TAG_GIVE_UP = "give_up";
    private static final String TAG_PAY = "pay";
    private XListView lv_content;
    private LoadView loadView;
    private final String TAG_REFRENSH = "refresh";
    private final String TAG_LOAD_MORE = "loadmore";
    private GameOrderListAdapter adapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_game);
        lv_content = (XListView) findViewById(R.id.xlv_content);
        loadView = (LoadView) findViewById(R.id.loadview);
        loadView.setOnReLoadClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadView.setStatus(LoadView.Status.loading);
                refresh();
            }
        });
        lv_content.setXListViewListener(this);
        lv_content.setRefreshTimeListener(this);
        adapter = new GameOrderListAdapter();
        lv_content.setAdapter(adapter);
        lv_content.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (parent.getItemAtPosition(position) instanceof GameOrder) {
                    Intent intent = new Intent(getApplicationContext(), GameParticipateInfoActivity.class);
                    intent.putExtra(AlbumActivity.UUID, ((GameOrder) parent.getItemAtPosition(position)).getUuid());
                    startActivity(intent);
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        onItemFirstShow();
    }

    private void refresh() {
        ResponseHandler handler = new ResponseHandler(TAG_REFRENSH);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        handler.setOnNeedLoginListener(this);
        NewsMode.obtainMyGames(handler, NewsMode.MODE_REFRESH, UserMode.getCurrentUserInfo(this).getToken());
    }

    private void loadmore() {
        ResponseHandler handler = new ResponseHandler(TAG_LOAD_MORE);
        handler.setOnSucceedListener(this);
        handler.setOnFailedListener(this);
        NewsMode.obtainMyGames(handler, NewsMode.MODE_LOAD_MORE, UserMode.getCurrentUserInfo(this).getToken());
    }

    @Override
    public void onFailed(String tag, ResponseHandler.FailedStatus status, int resultCode, String msg) {
        if (msg == null) {
            switch (status) {
                case DATA_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.tip_data_error);
                    break;
                case NETWORK_ERROR:
                    ToastUtil.show(getApplicationContext(), R.string.servererrortips);
                    break;
            }
        } else {
            ToastUtil.show(getApplicationContext(), msg);
        }

        if (TAG_REFRENSH.equals(tag)) {
            if (loadView.getStatus() != LoadView.Status.successed) {
                loadView.setStatus(status == ResponseHandler.FailedStatus.DATA_ERROR ? LoadView.Status.data_error : LoadView.Status.network_error);
            }
            lv_content.stopRefresh();
        }
        if (TAG_LOAD_MORE.equals(tag)) {
            lv_content.stopLoadMore();
        }
    }

    @Override
    public void onSucceed(String tag, boolean isCache, Object data) {
        if (TAG_REFRENSH.equals(tag)) {
            ArrayList<GameOrder> bean = (ArrayList<GameOrder>) data;
            refreshData(isCache, bean);
        } else if (TAG_LOAD_MORE.equals(tag)) {
            ArrayList<GameOrder> bean = (ArrayList<GameOrder>) data;
            loadMoreData(bean);
        } else if(TAG_PAY.equals(tag)){
            String datastr = (String) data;
        }else {
            refresh();
        }
    }

    /**
     * 刷新数据
     */
    private void refreshData(boolean isCache, ArrayList<GameOrder> beans) {
        if (!isCache) {
            if (beans == null || beans.size() == 0) {
                loadView.setStatus(LoadView.Status.not_data);
            } else {
                loadView.setStatus(LoadView.Status.successed);
                adapter.setOrders(beans);
            }
            lv_content.setSelection(0);
        }
        saveLastUpdateTime();
        lv_content.stopRefresh();
    }


    /**
     * 保存最后更新时间
     */
    private void saveLastUpdateTime() {
        SharedPreferences.Editor lastUpdateTimeEditor = getApplicationContext().getSharedPreferences(
                AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(),
                Context.MODE_PRIVATE).edit();
        lastUpdateTimeEditor.putLong(
                AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(),
                System.currentTimeMillis()).commit();
    }

    @Override
    public void onRefresh() {
        refresh();
    }


    /**
     * 加载更多
     */
    private void loadMoreData(List<GameOrder> beans) {
        if (beans == null || beans.size() == 0) {
            ToastUtil.show(getApplicationContext(), R.string.no_more, Toast.LENGTH_SHORT);
        } else {
            adapter.addOrders(beans);
        }
        lv_content.stopLoadMore();
    }

    @Override
    public void onLoadMore() {
        loadmore();
    }

    @Override
    public void onRefreshTime(TextView view) {
        view.setText(TimeUtil.obtainLastUpdateTimeStatuString(getApplicationContext(), getApplicationContext()
                .getSharedPreferences(
                        AppConstant.LastUpdateTimeKey.LAST_UPDATE_TIME.toString(), 0)
                .getLong(AppConstant.LastUpdateTimeKey.FINISHED_NEWS.toString(), 0)));
    }

    public void onItemFirstShow() {
        ArrayList<GameOrder> bean = NewsMode.getGameOrdersByCache(UserMode.getCurrentUserInfo(getApplicationContext()).getToken());
        if (bean != null) {
            if (bean != null) {
                if (bean.size() > 0) {
                    loadView.setStatus(LoadView.Status.successed);
                } else {
                    loadView.setStatus(LoadView.Status.not_data);
                }
                adapter.setOrders(bean);
            }
            lv_content.firstRefresh();
        } else {
            loadView.setStatus(LoadView.Status.loading);
            onRefresh();
        }
    }

    GameOrder order;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Uri bitmap = null;
        try {
            bitmap = CameraHead.callbackZoom(this, requestCode, resultCode, data, 0, 0);
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bitmap != null) {
            upLoad(bitmap);
        }
    }

    public void upLoad(Uri image) {
        ResponseHandler handler = new ResponseHandler(TAG_UPLOAD);
        handler.setOnSucceedListener(this);
        handler.setOnNeedLoginListener(this);
        handler.setOnFailedListener(this);
        handler.setOnUploadingListener(this);
        UserMode.uploadGamePhoto(new File(BitmapUtil.convertUri2FilePath(this, image)), order.getUuid(), UserMode.getCurrentUserInfo(this).getToken(), handler);
    }

    public void giveUp() {
        ResponseHandler handler = new ResponseHandler(TAG_GIVE_UP);
        handler.setOnSucceedListener(this);
        handler.setOnNeedLoginListener(this);
        handler.setOnFailedListener(this);
        handler.setOnUploadingListener(this);
        UserMode.giveUpGame(UserMode.getCurrentUserInfo(this).getToken(), order.getUuid(), handler);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ibtn_back:
                onBackPressed();
                break;
            case R.id.button1:

                if (v.getTag() instanceof GameOrder) {
                    order = (GameOrder) v.getTag();
                            payGame();
                }
                break;
            case R.id.button2:
                if (v.getTag() instanceof GameOrder) {
                    order = (GameOrder) v.getTag();
                    DialogUtil.showAskDialog(MyGamesActivity.this, "提示", "是否确认放弃参赛？", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            giveUp();
                        }
                    },false);
                }
                break;
        }
    }

    private void payGame() {
        Intent intent = new Intent(this,PaymentGameActivity.class);
        intent.putExtra(GameOrder.class.getSimpleName(),order);
        startActivity(intent);
    }

    @Override
    public void onNeedLogin(String tag) {
        startActivity(new Intent(MyGamesActivity.this, LoginActivity.class));
    }

    @Override
    public void onUploading(String tag, int progress) {

    }
}
